var fantasy = {};
fantasy.util = {};
fantasy.util.basePath = '/ticket/';
fantasy.util.rtime = function (){
	return new Date().getTime();
};

fantasy.util.captchEvent = function(captchaIdField){
	var captchaIdFieldImg = $("#" + captchaIdField +"Img");
	var captchaIdFieldInput = $("#" + captchaIdField +"Input");
	if(captchaIdFieldImg){
		captchaIdFieldImg.click(function(){
			fantasy.util.refreshCaptcha(captchaIdField);
		});
	}
	if(captchaIdFieldInput){
		captchaIdFieldInput.focus(function(){
			fantasy.util.refreshCaptcha(captchaIdField);
			captchaIdFieldInput.unbind('focus');
		});
	}
};

fantasy.util.refreshCaptcha = function(captchaIdField){
	var captchaIdFieldImg = $("#" + captchaIdField +"Img");
	var captchaIdField = $("#" + captchaIdField);
	if(captchaIdField.val()==""){//无ID，则产生一个ID
		fantasy.util.sendRequest(fantasy.util.basePath + "getCaptchaId.xhtml", {"r":fantasy.util.rtime()}, function(result){
			if(result.success) {
				captchaIdField.val(result.data);
				var curl = fantasy.util.basePath + "captcha.xhtml?captchaId=" + result.data + "&r=" + fantasy.util.rtime();
				captchaIdFieldImg.attr('src', curl);
			}else{
				alert("获取验证码出错，请重新获取！");
			}
		}, 'get');
	}else{
		var curl = fantasy.util.basePath + "captcha.xhtml?captchaId=" + captchaIdField.val() + "&r=" + fantasy.util.rtime();
		captchaIdFieldImg.attr('src', curl);
	}
};

fantasy.util.sendRequest = function(vurl, values, callback, vmethod){
	var _this = this;
	if(!_this.container){
		_this.container = {};
	}
	if(typeof values === "object"){
		if(fantasy.util.isEmptyObject(values)) vmethod = "get";
	}
	var hashinfo =  fantasy.util.hashCode(vurl, values);
	if(!vmethod){
		if(hashinfo.dataSize > 500){
			vmethod = "post";
		}else{
			vmethod = "get";
		}
	}
	var hashcode =hashinfo.code;
	$.ajax({
		type:vmethod,
		url:vurl,
		async:true,
		data: values,
		beforeSend:function(){
			if(_this.container[hashcode]){
				alert("数据正在处理中。。。");
				return false;
			}else{
				_this.container[hashcode] = true;
			}
			return true;
		},
		success:function(resText){
			try{
				if(callback){
					if(typeof resText === "object"){
						callback(resText);
					}else{
						callback(JSON.parse(resText));
					}
				}
			}catch(e){
				
			}
			_this.container[hashcode] = false;
		},
		error:function(response){
			try{
				var msg = "服务器异常！";
				if(response.status == 403){
					msg = "无权限操作！";
				}
				if(callback){
					var resText = {"success": false , "msg" : msg};
					callback(resText);
				}
			}catch(e){
				
			}
			_this.container[hashcode] = false;
		}
	});
};

fantasy.util.includeRequest = function(el, vurl, values, callback, vmethod){
	if(typeof values === "object"){
		if(fantasy.util.isEmptyObject(values)) vmethod = "get";
	}
	if(!vmethod){
		vmethod = "post";
	}
	$.ajax({
		type:vmethod,
		url:vurl,
		async:true,
		dataType: 'html',
		data: values,
		success:function(responseHTML){
			if(el && $("#" +el)){
				$("#" +el).html(responseHTML);
			}
			if(callback){
				var resText = {"success": true};
				callback(resText);
			}
		},
		error:function(response){
			var msg = "服务器异常！";
			if(response.status == 403){
				msg = "无权限操作！";
			}
			if(callback){
				var resText = {"success": false , "msg" : msg};
				callback(resText);
			}
		}
	});
};

fantasy.util.isEmptyObject=function(obj){
	for(var name in obj){return false;}
	return true;
};

fantasy.util.getValues = function (elid, valid, joinChar){
	var element = $("#" +elid);
	if(!element) return null;
	var dataElement = element.find(':input');
	var result = {}, checkKeyText = {};
	if(dataElement){
		var joinArray = null;
		if(!joinChar) joinArray = new Array();
		$.each(dataElement, function(index, el){
			var item = $(el);
			var name = item.attr('name');
			var mustTxt = item.attr('mustTxt');
			var checkName = (name == undefined || name == '');
			if(valid && !checkName && !(mustTxt == undefined || mustTxt == '')){
				checkKeyText[name] = mustTxt;
			}
			switch(el.tagName){
				case 'INPUT':
					if(!checkName){
						var tagType = item.attr('type');
						if(tagType == 'text' || tagType == 'hidden' || tagType =='password' || tagType == 'number'){
							result[name] = item.val();
						}else if(tagType == 'checkbox'){
							if(el.checked){
								if(joinArray != null){
									if(!result[name]) result[name] = joinArray;
									joinArray.push(item.val());
								}else{
									result[name] = result[name] ? (result[name] + joinChar + item.val()) : item.val();
								}
							}
						}else if(tagType == 'radio'){
							if(el.checked){
								result[name] = item.val();
							}
						}
					}
					break;
				case 'TEXTAREA':
					if(!checkName){
						result[name] = item.val();
					};
					break;
				case 'SELECT':
					if(!checkName){
						result[name] = item.find("option:selected").val();
					};
					break;
			
			}
		});
	}
	
	if(valid){
		if(Object.keys(checkKeyText).length > 0){
			for(var key in checkKeyText){
				if(!result[key] || result[key] == ''){
					return {'success':false,'msg':checkKeyText[key],'property':key};
				}
			}
		}
	}
	return {'success':true,'data': result};
};

/***
 * 获取当前访问地址中的参数(传key)
 * **/
fantasy.util.getRequestParams = function(name,link) {
	var url = window.location.search || link;
	if(url && url.indexOf(name) > 0){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"),
			r = url.substr(1).match(reg);
		return (r!=null)? r[2] : '';
	}else return "";
};
fantasy.util.getUrlParams = function(link){
	var url = window.location.search || link;
	if(url){
		var array = url.substr(1).split("&");
		var values = {};
		if(array){
			for(var i =0;i<array.length;i++){
				var item = array[i];
				keyValue = item.split("=");
				var key = keyValue[0];
				if(key && key != 'null'){
					values[key] = keyValue[1]?keyValue[1]:'';
				}
			}
		}
		return values;
	}else return {};
};
fantasy.util.hashCode = function(){
	var vurl = arguments[0];
	var values = arguments[1];
	var str = "";
	if(vurl){
		if(typeof str === "object"){
			str = JSON.stringify(str);
		}else{
			str = vurl;
		}
	}
	if(values){
		if(typeof values === "object"){
			str += JSON.stringify(values);
		}else{
			str += values;
		}
	}
	var h = 0;
    var len = str.length;
    var t = 2147483648;
    for (var i = 0; i < len; i++) {
        h = 31 * h + str.charCodeAt(i);
        if(h > 2147483647){
        	h %= t;
        }
    }
    return {"code":""+h,"dataSize":len};
};